package com.wdh.dbutil;

import com.mongodb.MongoClientSettings;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import com.mongodb.client.MongoCollection;
import org.bson.Document;

import java.util.Arrays;

public class MongoUtil {

    /**
     * Reuse Your Client
     * As each MongoClient represents a thread-safe pool of connections to the database,
     * most applications only require a single instance of a MongoClient, even across multiple threads.
     * */
    private static String mongoUrl = "mongodb://wdh.com:27017";

    private static MongoClient mongoClient;

    static {
        mongoClient = MongoClients.create(mongoUrl);
    }

    public static MongoCollection<Document> getCollection(String dbName, String collName){
        return mongoClient.getDatabase(dbName).getCollection(collName);
    }

    public static MongoClient getMongoClient(){
        return mongoClient;
    }

    /**
     * 1 已无认证方式启动mongo
     * 2 建立用户
     * 3 修改配置文件，开启安全认证
     * 4 重启mongodb
     * 参考 https://www.mongodb.com/docs/manual/tutorial/configure-scram-client-authentication/
     * */
    public static MongoClient getMongoClientWithPass(){
        String username = "wdh";
        String password = "333888";
        String authDb = "admin";
        String host = "127.0.0.1";
        int port = 27017;
        MongoCredential credential = MongoCredential.createCredential(username, authDb, password.toCharArray());
        MongoClient mongoClient = MongoClients.create(
                        MongoClientSettings.builder()
                                .applyToClusterSettings(builder ->
                                        builder.hosts(Arrays.asList(new ServerAddress(host,port))))
                .credential(credential)
                .build());
        return mongoClient;
    }
}
